package com.markus.code.newcode;

import com.markus.code.图.图2.Node;

/**
 * Author:markusZhang
 * Date:Create in 2020/9/6 16:00
 * todo: 合并两个链表
 */
public class MergeTwoLists {
    public static class ListNode{
        int val;
        ListNode next;
        public ListNode(int val){
            this.val = val;
        }
    }
    /**
     *
     * @param l1 ListNode类
     * @param l2 ListNode类
     * @return ListNode类
     */
    public ListNode mergeTwoLists (ListNode l1, ListNode l2) {
        // write code here
        if (l1 == null){
            return l2;
        }
        if (l2 == null){
            return l1;
        }
        ListNode l = new ListNode(-1);
        ListNode pre = l;
        while(l1 != null && l2 != null){
            if (l1.val <= l2.val){
                ListNode next = l1.next;
                l.next = l1;
                l1 = next;
            }else{
                ListNode next = l2.next;
                l.next = l2;
                l2= next;
            }
            l = l.next;
        }
        if (l1 != null){
            l.next = l1;
        }
        if (l2 != null){
            l.next = l2;
        }
        return pre.next;
    }

    private void printNode(ListNode head){
        while(head != null){
            System.out.print(head.val + " ");
            head = head.next;
        }
    }

    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        node1.next = new ListNode(3);
        node1.next.next = new ListNode(5);
        node1.next.next.next = new ListNode(7);
        node1.next.next.next.next = new ListNode(9);
        ListNode node2 = new ListNode(2);
        node2.next = new ListNode(4);
        node2.next.next = new ListNode(6);
        node2.next.next.next = new ListNode(8);
        node2.next.next.next.next = new ListNode(10);
        MergeTwoLists demo = new MergeTwoLists();
        ListNode node = demo.mergeTwoLists(node1, node2);
        demo.printNode(node);
    }
}
